<template>
  <!-- 主容器 -->
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="字典名称" prop="dictName">
        <el-input
          v-model="queryParams.dictName"
          placeholder="请输入字典名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="字典类型" prop="dictType">
        <el-input
          v-model="queryParams.dictType"
          placeholder="请输入字典类型"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="字典状态" clearable style="width: 240px">
          <el-option v-for="item in dict.type.sys_normal_disable" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
    </el-form>

    <!-- 按钮组 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" @click="handleQuery">搜索</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button @click="resetQuery">重置</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain @click="handleAdd" v-p="['system:dict:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          :disabled="ids.length > 1 || ids.length === 0"
          @click="handleUpdate"
          v-p="['system:dict:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain :disabled="ids.length === 0" @click="handleDelete" v-p="['system:dict:remove']"
          >删除</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain @click="handleExport"
          v-p="['system:dict:export']">导出</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" plain @click="handleRefreshCache" v-p="['system:dict:remove']">刷新缓存</el-button>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="typeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="字典编号" align="center" prop="dictId" />
      <el-table-column label="字典名称" align="center" prop="dictName" :show-overflow-tooltip="true" />
      <el-table-column label="字典类型" align="center" :show-overflow-tooltip="true">
        <template v-slot="scope">
          <router-link :to="'/system/dict-data/index/' + scope.row.dictId" class="link-type">
            <span>{{ scope.row.dictType }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template v-slot="scope">
          <el-tag type="" v-if="scope.row.status === '0'">正常</el-tag>
          <el-tag type="danger" v-else>停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button type="primary" link @click="handleUpdate(scope.row)" v-p="['system:dict:edit']">修改</el-button>
          <el-button type="primary" link @click="handleDelete(scope.row)" v-p="['system:dict:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @update:page="handlePageChange"
      @update:limit="handlePageSizeChange"
    />

    <!-- 对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="字典名称" prop="dictName">
          <el-input v-model="form.dictName" placeholder="请输入字典名称" />
        </el-form-item>
        <el-form-item label="字典类型" prop="dictType">
          <el-input v-model="form.dictType" placeholder="请输入字典类型" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="item in dict.type.sys_normal_disable" :key="item.value" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import type { FormInstance } from "element-plus";
import type { DictEntry } from "@/typings";
import { ref, onMounted, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import Pagination from "@/components/pagination/Pagination.vue";
import {
  addDictTypeApi,
  delDictTypeApi,
  getDictTypeInfoApi,
  getDictTypeListApi,
  refreshCacheApi,
  updateDictTypeApi
} from "@/api";

const ids = ref<number[]>([]);
const typeList = ref<DictEntry[]>([]);
const loading = ref(false);
const open = ref(false);
const title = ref("");
const form = reactive<DictEntry | any>({
  dictName: "",
  dictType: "",
  status: "0",
  remark: ""
});
const rules = {
  dictName: [
    { required: true, message: "请输入字典名称", trigger: "blur" },
    { min: 1, max: 100, message: "长度在 1 到 100 个字符", trigger: "blur" }
  ],
  dictType: [
    { required: true, message: "请输入字典类型", trigger: "blur" },
    { min: 1, max: 100, message: "长度在 1 到 100 个字符", trigger: "blur" }
  ],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
  remark: [{ min: 0, max: 200, message: "长度在 0 到 200 个字符", trigger: "blur" }]
};

/**
 * 查询表单引用
 */
const queryForm = ref<FormInstance>();
const queryParams = reactive({
  dictName: "",
  dictType: "",
  status: "",
  pageNum: 1,
  pageSize: 10,
  beginTime: ""
});
/**
 * 执行搜索
 */
const handleQuery = () => {
  getDictTypeList();
};
/**
 * 重置查询条件
 */
const resetQuery = () => {
  queryForm.value?.resetFields();
  getDictTypeList();
};

/**
 * 新增字典
 */
const handleAdd = () => {
  title.value = "新增字典";
  open.value = true;
};
/**
 * 更新字典
 */
const handleUpdate = async (row: DictEntry | any) => {
  try {
    title.value = "修改字典";
    const postId = row.dictId || ids.value;
    const res = await getDictTypeInfoApi(postId);
    if (res.code === 200) {
      Object.assign(form, res.data);
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    console.error(error);
  }
  open.value = true;
};
/**
 * 删除字典
 */
const handleDelete = (row: DictEntry | any) => {
  try {
    if (ids.value.length > 0) {
      row.dictId = ids.value.join(",");
    }
    ElMessageBox.confirm("确定删除所勾选的字典吗？删除之后数据将无法恢复", "系统提示", {
      type: "warning"
    }).then(async () => {
      const res = await delDictTypeApi(row.dictId);
      if (res.code === 200) {
        ElMessage.success("删除成功");
        getDictTypeList();
      } else {
        ElMessage.error(res.message);
      }
    });
  } catch (error) {
    ElMessage.error("delete Data error");
  }
};
/**
 * 刷新缓存
 */
const handleRefreshCache = async () => {
  try {
    const res = await refreshCacheApi();
    if (res.code === 200) {
      ElMessage.success("刷新缓存成功");
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    console.error(error);
  }
};
/**
 * 选择变更
 */
const handleSelectionChange = (row: DictEntry[]) => {
  ids.value = row.map((item: DictEntry) => item.dictId);
};

/**
 * 表单引用
 */
const formRef = ref<FormInstance>();
/**
 * 添加字典
 */
const addDict = async () => {
  const res = await addDictTypeApi(form);
  if (res.code === 200) {
    ElMessage.success("新增字典成功");
    open.value = false;
    formRef.value!.resetFields();
    Object.assign(form, {});
    getDictTypeList();
  } else {
    ElMessage.error(res.message);
  }
};
/**
 * 更新字典
 */
const updateDict = async () => {
  const res = await updateDictTypeApi(form);
  if (res.code === 200) {
    ElMessage.success("修改字典成功");
    formRef.value!.resetFields();
    Object.assign(form, {});
    open.value = false;
    getDictTypeList();
  } else {
    ElMessage.error(res.message);
  }
};
/**
 * 提交表单
 */
const submitForm = () => {
  if (!formRef.value) return;
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return;
    if (form.dictId) {
      updateDict();
    } else {
      addDict();
    }
  });
};
/**
 * 取消操作
 */
const cancel = () => {
  open.value = false;
  formRef.value!.resetFields();
  Object.assign(form, {});
};

/**
 * 分页
 */
const total = ref(0);
/**
 * 处理分页变更
 */
const handlePageChange = (page: number) => {
  queryParams.pageNum = page;
};
/**
 * 处理每页条目数量变更
 */
const handlePageSizeChange = (size: number) => {
  queryParams.pageSize = size;
};

// 状态
const dict: { type: { [key: string]: { value: string; label: string }[] } } = {
  type: {
    sys_normal_disable: [
      { value: "0", label: "正常" },
      { value: "1", label: "停用" }
    ],
    sys_show_hide: [
      { value: "0", label: "显示" },
      { value: "1", label: "隐藏" }
    ]
  }
};

/**
 * 获取字典类型列表
 */
const getDictTypeList = async () => {
  try {
    loading.value = true;
    const res = await getDictTypeListApi(queryParams);
    if (res.code === 200) {
      typeList.value = res.data;
      total.value = res.data.total;
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    console.error(error);
  } finally {
    loading.value = false;
  }
};

/**
 * 组件挂载后，获取字典类型列表
 */
onMounted(() => {
  getDictTypeList();
});
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}
</style>
